#!/usr/bin/env python3
from __future__ import print_function
import xlrd
from datetime import datetime, date
import re
import sys
import os
from apostl import Start_Fill

if len(sys.argv) != 3:
    print('	{} [input.excel] [start-row-number]'.format(sys.argv[0]))
    sys.exit(-1)

start = int(sys.argv[2]) - 1
#total = int(sys.argv[3]) 
total = 1
#today = date.today().strftime('%Y-%m-%d') + '-apostl'
#dstdir = os.path.join("out", today)
#if not os.path.exists(dstdir):
#    os.makedirs(dstdir)

rb = xlrd.open_workbook(sys.argv[1])
sheet = rb.sheet_by_index(0)
rows = sheet.nrows
cols =  sheet.ncols
#0 empty 1 string 2 number 3 date
#for x in range(start, rows):
for x in range(start, start + total):
    shit = False
    dualtest = False
    test_date = ""
    test_date_month = 0
    test_date_day = 0
    test_date_year = 2020
    report_date  = ""
    report_date_month = 0
    report_date_day = 0
    report_date_year = 2020
    first_name, last_name = "", ""
    birth = ""
    gender = ""
    tel = ""
    email = ""
    licence  = ""
    address = ""
 
    city  = ""
    street = ""
    zipcode = ""
    state = ""
    start = ord('A')

    for y in range(cols):
        cell = sheet.cell(x, y)
        if y == (ord('F')  - start) and cell.ctype == 1:
            tmp = cell.value
            order_id = "{:.0f}".format(tmp) 
            print(order_id, end="|")
        if y == (ord('F')  - start) and cell.ctype == 2:
            tmp = cell.value
            order_id = int(tmp)
            print(order_id, end="[")
        """
        if y == 4 and cell.ctype == 3:
            cell_tuple = xlrd.xldate_as_tuple(cell.value, datemode=0)
            test_date = (date(*cell_tuple[:3]).strftime('%m/%d/%Y'))
            test_date_month = "{:02d}".format(cell_tuple[1])
            test_date_day = "{:02d}".format(cell_tuple[2])
            test_date_year = cell_tuple[0]
            print(test_date, end="|")

        if y == 5 and cell.ctype == 3:
            cell_tuple = xlrd.xldate_as_tuple(cell.value, datemode=0)
            report_date = (date(*cell_tuple[:3]).strftime('%m/%d/%Y'))
            report_date_month = "{:02d}".format(cell_tuple[1])
            report_date_day = "{:02d}".format(cell_tuple[2])
            report_date_year = cell_tuple[0]
            print(report_date, end="|")
        """

        if y == (ord('I')  - start) and cell.ctype == 1:
            how = cell.value.count(' ')
            second_name = ""
            if how == 1:
                first_name, last_name = cell.value.split(' ')
            elif how == 2:
                first_name, second_name, last_name = cell.value.split(' ')
            first_name = first_name + " " + second_name
            first_name = first_name.strip()
            last_name = last_name.strip()
            print(first_name , last_name, end="|")

        if y == (ord('J')  - start) and cell.ctype == 3:
            cell_tuple = xlrd.xldate_as_tuple(cell.value, datemode=0)
            birth = (date(*cell_tuple[:3]).strftime('%m/%d/%Y'))
            print(birth, end="|")

        if y == (ord('K')  - start) and cell.ctype == 1:
            gender = cell.value
            gender = gender.lower()
            print(gender, end="|")

        if y == (ord('L')  - start) and cell.ctype == 1:
            tel = cell.value
            print(tel, end="|")
        if y == (ord('L')  - start) and cell.ctype == 2:
            tmp = cell.value
            tel = "{:.0f}".format(tmp) 
            print(tel, end="|")

        if y == (ord('M')  - start) and cell.ctype == 1:
            email = cell.value
            print(email, end="|")
        """
        if y == 12 and cell.ctype == 1:
            licence = cell.value
            print(licence, end="|")
        if y == 12 and cell.ctype == 2:
            licence = "{:.0f}".format(cell.value)
            print(licence, end="|")
        """
        if y == (ord('O')  - start) and cell.ctype ==1 :
            address = cell.value
            print(address )

    tmp = re.search("[0-9]{5}$", address)
    if tmp:
        zipcode = tmp.group()
    else:
        shit = True
    tmp = re.findall("[A-Z]{2}",address)
    if tmp:
        state = tmp[-1]
    else:
        shit = True

    #tmp = re.search("([A-Z][a-z]+\s?)+,?\s?[A-Z]{2},?\s?\d{5}",address)
    tmp = re.search("(([A-Z][a-z]+\s?){1,2}),?\s?[A-Z]{2},?\s?\d{5}",address)
    if tmp:
       city = tmp.group(1)
    else:
        shit = True

    if len(city) > 0:
        where = address.find(city)
        street = address[:where]

    if len(street) < 10:
        where = address.find(state)
        street = address[:where]
        if len(street) < 10:
            street = address

    data_dict = {
   'last_name': last_name,  #first name
   'first_name': first_name,  #second name
   'dob': birth,
   'gender': 'M',
   'email_id': email,  #email
   'phone': tel, #phone
   'address': street,  #
   'city': city,  #city
   'live_in_los_angeles':"No",
   'state': state,  #state
   'zip_code': zipcode,
   'order_id': order_id,

   'country':'300', #USA
   'patient_race':"Asian",
   'patient_ethnicity':"315" #Non-Hispanic
    }
    if gender == "female":
        data_dict['gender'] = 'F'
    if city.find('Los') >= 0:
        data_dict['live_in_los_angeles'] = 'Yes'

    print(data_dict)
    print(sys.argv[2], end="--")
    Start_Fill(**data_dict)



